package com.tepth.busfix.main.partsearch;

import android.content.Intent;
import android.support.v7.widget.Toolbar;
import android.text.InputType;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.tepth.busfix.R;
import com.tepth.busfix.base.BaseActivity;
import com.tepth.busfix.bean.reponse.Trouble;
import com.tepth.busfix.bean.reponse.TroubleClassification;
import com.tepth.busfix.bean.reponse.TroubleContent;
import com.tepth.busfix.config.SpKey;
import com.tepth.busfix.main.login.LoginActivity;
import com.tepth.busfix.tools.SPUtils;
import com.tepth.busfix.view.dialog.DialogDelegate;
import com.tepth.busfix.view.dialog.SweetAlertDialogDelegate;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.util.ArrayList;

import butterknife.BindView;
import xyz.sahildave.widget.Utils;

/**
 * Created by pc on 2017/3/17.
 */

public class PartSearchActivity extends BaseActivity
        implements PartSearchContract.View {
    public static final String EXTRA_NAME = "action";
    public static final String TROUBLE = "trouble";
    public static final int RESULT_CODE = 2;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.et_search)
    EditText editTextSearch;
    @BindView(R.id.id_tag_flow_layout)
    TagFlowLayout tagFlowLayout;
    @BindView(R.id.tv_action)
    TextView tvAction;
    @BindView(R.id.list_view)
    ListView listView;
    @BindView(R.id.layout_empty)
    LinearLayout layoutEmpty;
    DialogDelegate dialogDelegate;
    //推荐的部件Accessory个数
    private int mRecommendAcSize;
    //推荐的部件componentSize
    private int mRecommendCoSize;
    //搜索的部件Accessory个数
    private int mSearchAcSize;
    //搜索的部件ComponentSize
    private int mSearchCoSize;
    //传递过来的操作
    private TroubleContent.Operation mOperation;
    private PartSearchPresenter mPresenter;
    private PartSearchModel mModel;
    private TroubleClassification mClassification;
    private long mTroubleTypeId;
    private Trouble mTrouble;

    @Override
    public void onNetworkError(String msg) {
        dialogDelegate.stopProgressWithFailed(msg, msg);
    }

    @Override
    public void onError(String msg) {
        dialogDelegate.stopProgressWithFailed(msg, msg);
    }

    @Override
    public void onTokenInvalid(String msg) {
        dialogDelegate.stopProgressWithWarning(msg, "请重新登录", new DialogDelegate.OnDialogListener() {
            @Override
            public void onClick() {
                Intent intent = new Intent(PartSearchActivity.this, LoginActivity.class);
                intent.putExtra("reload", "reload");
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            }
        });
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_part_search;
    }

    @Override
    public void initView() {
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        dialogDelegate = new SweetAlertDialogDelegate(this);
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.menu_search:
                        onSearch(editTextSearch.getText().toString().trim());
                        break;
                }
                return true;
            }
        });
        editTextSearch.setInputType(InputType.TYPE_CLASS_TEXT);
        editTextSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    onSearch(editTextSearch.getText().toString().trim());
                    Utils.hideInputMethod(v);
                    return true;
                }
                return false;
            }
        });

        Intent intent = getIntent();
        mOperation = (TroubleContent.Operation) intent.getSerializableExtra(EXTRA_NAME);
        mTrouble = (Trouble) intent.getSerializableExtra(TROUBLE);
        tvAction.setText(getString(R.string.search_result) + "(" + mOperation.getName() + ")");
        mPresenter.getCommonComponents();
        dialogDelegate.showProgressDialog(true, getString(R.string._loading));
    }

    @Override
    public void setPresenter() {
        mPresenter = new PartSearchPresenter();
        mModel = new PartSearchModel();
        mPresenter.setVM(this, mModel);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.search, menu);
        toolbar.getMenu().findItem(R.id.menu_setting).setVisible(false);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                setResult(0, new Intent());
                finish();
                break;
        }
        return true;
    }

    @Override
    public String getAuthKey() {
        return SPUtils.getString(this, SpKey.KEY_AUTH_KEY, "");
    }

    @Override
    public String getName() {
        return editTextSearch.getText().toString().trim();
    }

    @Override
    public int getCount() {
        return 20;
    }

    public void onSearch(String key) {

        if (!key.isEmpty()) {
            mPresenter.search();
            dialogDelegate.showProgressDialog(true, "正在搜索,请稍候...");
        }

    }

    @Override
    public void showSearchResult(int accessorySize, int componentSize, ArrayList<TroubleContent.Part> list) {
        dialogDelegate.clearDialog();
        if (list == null || list.isEmpty()) {
            layoutEmpty.setVisibility(View.VISIBLE);
            listView.setVisibility(View.GONE);
        } else {
            mSearchAcSize = accessorySize;
            mSearchCoSize = componentSize;
            layoutEmpty.setVisibility(View.GONE);
            listView.setVisibility(View.VISIBLE);
            final ArrayAdapter<TroubleContent.Part> adapter = new ArrayAdapter<>(this, R.layout.item_text, list);
            listView.setAdapter(adapter);
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    TroubleContent.Part part = adapter.getItem(position);
                    setIntentData(position, mSearchAcSize, part);
                }
            });
        }

    }

    @Override
    public void showCommonComponents(int accessorySize, int componentSize, ArrayList<TroubleContent.Part> list) {
        dialogDelegate.clearDialog();
        if (!list.isEmpty()) {
            mRecommendAcSize = accessorySize;
            mRecommendCoSize = componentSize;
            setTagLayout(list);
        }
    }

    private void setTagLayout(ArrayList<TroubleContent.Part> list) {
        final LayoutInflater inflater = LayoutInflater.from(this);
        final TagAdapter<TroubleContent.Part> tagAdapter = new TagAdapter<TroubleContent.Part>(list) {
            @Override
            public View getView(FlowLayout parent, int position, TroubleContent.Part part) {
                TextView tv = (TextView) inflater.inflate(R.layout.view_tv,
                        parent, false);
                tv.setText(part.getName());
                return tv;
            }
        };
        tagFlowLayout.setMaxSelectCount(1);
        tagFlowLayout.setAdapter(tagAdapter);
        tagFlowLayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                //TODO 需要知道选中的是哪个list里面的数据
                TroubleContent.Part part = tagAdapter.getItem(position);
                setIntentData(position, mRecommendAcSize, part);
                return false;
            }
        });
    }

    private void setIntentData(int position, int referenceValue, TroubleContent.Part part) {
        Intent intent = new Intent();
        if (position <= referenceValue - 1) {
            intent.putExtra("type", "Accessory");
        } else {
            intent.putExtra("type", "component");
        }
        intent.putExtra("operation", mOperation);
        intent.putExtra("part", part);
        intent.putExtra(TROUBLE, mTrouble);
        setResult(RESULT_CODE, intent);
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPresenter.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //TODO 刷新界面
    }
}
